<template>
	<view class="container">

		<!-- 地址块 -->
		<view class="areaContent" @tap="toEditAddress">
			<view class="iconContent">

			</view>
			<view class="areaInfo">
				<block v-if="existDefaultAddress">
					<view class="areaTitle">
						{{addressInfo.serverAddressConsigneeProvinceName}}{{addressInfo.serverAddressConsigneeCityName}}{{addressInfo.serverAddressConsigneeDistrictName}}{{addressInfo.serverAddressConsigneeDetail}}
					</view>
					<view class="personInfo">
						<text class="name">{{addressInfo.serverAddressConsigneeName}} </text>
						<text class="phone">{{addressInfo.serverAddressConsigneePhone}}</text>
					</view>
				</block>
				<block v-else>
					<view class="areaTitle">
						请填写收货地址
					</view>
					<view class="personInfo">
						点击填写
					</view>
				</block>
			</view>

			<view class="icon">
				<uni-icons type="forward" size="15"></uni-icons>
			</view>
		</view>



		<!-- 商品卡片 -->
		<view class="replishList">
			<view class="goodItem" v-for="subItem in selectedList">
				<view class="goodImage">
					<image :src="subItem.productDetailImg" mode="aspectFill"></image>
				</view>
				<view class="goodDesc">
					<view class="goodName">
						{{subItem.productName}}
					</view>

					<view class="specific">
						{{subItem.productDetailSpecifications}}
					</view>

					<view class="priceAndNum">
						<!-- 价格区域 -->
						<view class="price">
							<view class="nowPrice">
								￥{{caluateDiscount(subItem.productDetailPrice) }}
							</view>
						</view>
						<!-- 进步器区域 -->
						<view class="steeper">
							<steeper :itemNum="subItem.quantity" :limitStock="subItem.cloudWarehouseStock"
								@add="num=>toAdd(num,subItem.id)" @minus="num=>toMinus(num,subItem.id)"
								@blur="num=>toBlur(num,subItem.id)">
							</steeper>

						</view>

					</view>


				</view>
			</view>

		</view>



		<!-- 运费与备注板块 -->
		<view class="deliverDetail">
			<view class="deliverPrice">
				<text>运费</text>
				<text class="price">￥{{Number(develiverFee).toFixed(2) }}</text>
			</view>

			<view class="remark">
				<text class="textContent">订单备注</text>

				<view class="remarkDisplay">

				</view>

				<view class="displayText">
					<input type="text" v-model="remark" placeholder="无备注">
					<uni-icons type="forward" size="15" style="text-align: center;"></uni-icons>
				</view>





			</view>
		</view>

		<!-- 支付板块 -->
		<view class="payContent">

			<view class="payTitle">
				付款方式
			</view>
			<view class="payItem">
				<view class="title">
					<view class="commssionIcon">

					</view>
					<text
						:class="commssionAmount<totalPrice&&freeFlag===false?'insufficient':''">佣金支付(余额￥{{commssionAmount}})</text>
				</view>
				<view class="selectPay" :class="payStatus===0?'selected':'unselected'" @click="changePayType(0)">

				</view>
			</view>
			<view class="payItem">
				<view class="title">
					<view class="wxIcon">

					</view>
					<text>微信支付</text>
				</view>
				<view class="selectPay" :class="payStatus===1?'selected':'unselected'" @click="changePayType(1)">

				</view>
			</view>

		</view>



		<!-- 订单提交板块 -->
		<view class="confirmFooter">
			<view class="confirmContent">
				<view class="textContent">
					<text>合计</text>
					<text class="price">￥{{Number(develiverFee).toFixed(2)}}</text>
				</view>
				<button class="submit" type="submit" @click="confirm()">提交订单</button>
			</view>
		</view>

	</view>
</template>

<script>
	// 导入测试数据
	import {
		list
	} from '@/mock/cart.js';
	import steeper from '@/components/stepper.vue'
	import * as ordersApi from '@/api/orders/orders.js'
	import * as ProductApi from '@/api/product/product.js'
	import * as serverOrder from '@/api/serviceOrder/serviceOrder.js'
	import * as commssionApi from '@/api/commssion/commssion.js'
	import * as serverAddressApi from '@/api/serverAddress/serverAddress.js'
	let lastRequestTime = 0;
	const requestInterval = 1000; // 设置请求的最小间隔时间，例如1000毫秒
	export default {
		components: {
			steeper
		},
		data() {
			return {
				//判断是云仓提货生成的订单还是提货订单那里传来的支付订单为选货的订单
				//用来放提货订单那里传来的VO
				infoStatus: true,
				list: list,
				subId: null,
				quantity: 50,
				confirmPrice: 0,
				addressInfo: null,

				//初始化地址列表
				addressList: null,
				existDefaultAddress: false,
				//将要购买的商品列表,用来渲染
				selectedList: [],
				totalPrice: 0,
				//如果用户选择了地址那么回传地址Id,重新渲染订单信息,
				addressId: null,

				changeAddressId: null,
				// 生成订单后后台传回的需要唤起微信支付的数据
				List: {
					appId: "",
					signType: "RSA",
					package: "",
					nonceStr: "",
					timeStamp: "",
					paySign: ""
				},


				//备注
				remark: '',
				//表示支付方式0表示佣金支付
				payStatus: 0,
				//用金余额

				commssionAmount: 0,
				//当商品总价大于佣金总额时禁用佣金支付
				isDisableCommssion: false,
				// 表示是否用的是默认地址 默认地址提货免运费
				freeFlag: false

			}
		},
		computed: {
			totalPriceConfirm() {
				return Number(this.quantity * this.confirmPrice) 
			},
			totalQuantity() {
				return this.selectedList.reduce((total, item) => {
					return  Number(total)  + ( Number(item.quantity)|| 0);
				}, 0);

			},

			develiverFee() {
				if (this.freeFlag === true) {
					return 0;
				}
				if (this.totalQuantity <= 2) {
					return 8; // 1-2盒的运费为8元
				} else if (this.totalQuantity <= 4) {
					return 15; // 3-4盒的运费为15元
				} else if (this.totalQuantity <= 6) {
					return 20; // 5-6盒的运费为20元
				} else {
					return 3 * this.totalQuantity; // 6盒以上的情况：3元*盒数
				}
			}



		},
		onLoad(options) {
			const paramsStr = options.params || null; // 获取URL查询参数中的params字段
			//接收个人中心传来的订单类型
			if (paramsStr != null) {
				const receivedParams = JSON.parse(paramsStr);
				this.selectedList = receivedParams.selectedList
				this.totalPrice = receivedParams.totalPrice;
				
			}


			// 地址页面传回的待切换ID
			// this.changeAddressId = receivedParams.addressId;
			this.addressInit();
			this.getServiceInfo();

		},
		onShow() {
			
			this.addressInit();

		},
		methods: {
			//根据服务商类型进行打折
			caluateDiscount(price) {
				
				if (this.$globalData.userType !== null) {
					
					if (this.$globalData.userType === 1) {
						return Number(0.5 * price).toFixed(2)
					} else {
						
						return Number(0.4 * price).toFixed(2)
					}
				}
			},
			// 获取佣金信息
			async getServiceInfo() {
				const res = await commssionApi.getServerKickbackByServerUserId();
				
				if (res.data.code === 200) {
					const serviceInfo = res.data.data;
					if (serviceInfo != null) {
						this.commssionAmount = serviceInfo.serverKickbackRemainAmount;

						if (this.commssionAmount < this.totalPrice) {
							
							this.changePayType(1)
						}



					}

				} else if (res.data.code === 270) {
					this.changePayType(1);
				}

			},

			//计算商品总价
			getSelectedTotalPrice() {
				this.totalPrice = this.selectedList.reduce((total, item) => {
					// 计算每个子商品的价格，productDetailPrice * quantity
					const itemTotal = item.productDetailPrice * item.quantity;
					// 累加到总和上
					return total + itemTotal;
				}, 0); // 初始总和为 0
			},

			// 在补货清单对子商品的数量进行加减
			toAdd(num, id) {
				
				this.selectedList.forEach(item => {
					if (item.id === id) {
						
						item.quantity = num;
					}
				});
				this.getSelectedTotalPrice()

			},

			toMinus(num, id) {
				this.selectedList.forEach(item => {
					if (item.id === id) {
						
						item.quantity = num;
					}
				});
				this.getSelectedTotalPrice()
			},
			toBlur(num, id) {
				this.selectedList.forEach(item => {
					if (item.id === id) {
						
						item.quantity = num;
					}
				});
				this.getSelectedTotalPrice()
			},
			async addressInit() {
				const res = await serverAddressApi.selectServerAddressBook();
				
				this.addressList = res.data.data;
				//地址表里总是会有一个默认地址我们只需要判断地址列表是否为空就行了
				if (this.addressList != null || this.addressList.length != 0) {
					if (this.$globalData.serverDeleteFlag === true) {
						this.$globalData.selectedServerAddress = null;
						this.$globalData.serverDeleteFlag = null;
					}


					if (this.$globalData.selectedServerAddress === null) {

						this.addressInfo = this.addressList.find(item => item.serverAddressServerUserDefault == 1);
						this.freeFlag = true;
						this.develiverFee = 0;

					} else {
						this.addressInfo = this.addressList.find(item => item.id === this.$globalData
							.selectedServerAddress)
						if (this.addressInfo.serverAddressServerUserDefault === 1) {

							this.freeFlag = true;
							this.payStatus = 0;
							this.develiverFee = 0;
						} else {
							this.freeFlag = false;
							this.payStatus = 1;
						}

					}

					this.addressId = this.addressInfo.id;
					this.existDefaultAddress = true;
				}
			},


			changePayType(payType) {
				if (this.freeFlag === true) {
					this.payStatus = 0
					return;
				}

				if ((this.totalPrice > this.commssionAmount) && payType === 0 && (this.freeFlag === false)) {
					return uni.$showMsg('佣金余额不足')
				}
				this.payStatus = payType;
			},
			// 跳转地址修改
			toEditAddress() {
				const currentTime = new Date().getTime();
				if (currentTime - lastRequestTime < requestInterval) {
					return uni.$showMsg('操作过于频繁'); // 这将阻止请求继续执行
				}
				lastRequestTime = currentTime; // 更新上一次请求时间
				uni.$toPage('/subpkg/ServiceProvider/serviceAddressList/serviceAddressList', {
					isChooseStatus: true
				})
			},


			// 提交订单结算界面
			async confirm() {
				if (this.existDefaultAddress === false) {
					return uni.$showMsg('请先选择地址')
				}
				if (this.selectedList.length === 0) {
					return uni.$showMsg('操作过快')
				}
				const currentTime = new Date().getTime();
				if (currentTime - lastRequestTime < requestInterval) {
					return uni.$showMsg('操作过于频繁'); // 这将阻止请求继续执行
				}
				lastRequestTime = currentTime; // 更新上一次请求时间
				
				
				const ordersDetailSimpleList = this.selectedList.map(item => {
					return {
						backupProductDetailId: item.backupProductDetailId,
						ordersDetailNumber: item.quantity
					};
				});

				const generateOrders = {
					serverAddressBookId: this.addressId,
					serverUsersOutOrdersRetailAmount: Number(this.totalPrice).toFixed(2),
					serverUsersOutOrdersRealAmount: this.caluateDiscount(this.totalPrice),
					serverUsersOutOrdersTransportAmount: Number(this.develiverFee).toFixed(2),
					ordersDetailSimpleList: ordersDetailSimpleList,
					serverUsersOutOrdersRemark: this.remark,
					serverUsersOutOrdersPayWayStatus: this.payStatus
				}


				//生成订单从后台拿支付数据
				const res = await serverOrder.pickUpCloudWarehouse(generateOrders);
				console.log(res)
				if (res.data.code === 200) {
					if (this.payStatus === 1) {
						
						let orderResponseData = res.data.data.stringStringMap;
						uni.$WxPay(orderResponseData).then(response => {
								// 支付成功的处理
								uni.$toPage(
									'/subpkg/ServiceProvider/pickUpTansferPage/pickUpTansferPage', {}, false,
									false, true)
							})
							.catch(error => {
								// 支付失败的处理
								uni.$showMsg('支付失败')
								uni.$toPage('/subpkg/ServiceProvider/serviceOrderRecord/serviceOrderRecord', {
									flag: 0
								}, false, false, true);

							});



					} else {
						uni.$toPage('/subpkg/ServiceProvider/pickUpTansferPage/pickUpTansferPage', {}, false, false,
							true)
					}


				} else {
					return uni.$showMsg('支付失败')
				}







			},


		}
	}
</script>

<style scoped lang="scss">
	page {
		background-color: rgba(235, 236, 237, 1);
	}

	.container {
		width: 100%;
		padding-bottom: 300rpx;
		overflow: scroll;
		display: flex;
		flex-wrap: wrap;
		flex-direction: column;
		align-items: center;
		box-sizing: border-box;

		// 地址板块
		.areaContent {


			margin-top: 30rpx;
			box-sizing: border-box;
			background-color: rgba(255, 255, 255, 1);
			width: 694rpx;
			position: relative;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			border-radius: 14rpx;
			background: rgba(255, 255, 255, 1);
			margin-bottom: 10rpx;
			box-sizing: border-box;

			.iconContent {
				margin-left: 24rpx;
				width: 32rpx;
				height: 32rpx;
				box-sizing: border-box;
				background: url(/static/cart/spcar_icon_address_default@2px.png.png);
				background-size: cover;
			}

			.areaInfo {
				margin-top: 20rpx;
				margin-bottom: 20rpx;
				padding-top: 0rpx;
				box-sizing: border-box;

				.areaTitle {
					margin-top: 0rpx;
					width: 504rpx;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.personInfo {
					box-sizing: border-box;
					margin-top: 16rpx;
					width: 231rpx;
					font-size: 24rpx;
					color: rgba(56, 56, 56, 1);
					white-space: nowrap;

					.name {
						margin-right: 5rpx;
					}

				}
			}

			.icon {

				padding-right: 28rpx;
			}
		}


		.replishList {
			// 商品列表
			box-sizing: border-box;
			height: calc(100% - 176rpx);
			display: flex;
			flex-direction: column;
			padding-top: 20rpx;
			align-items: center;
			overflow: auto;

			.goodItem {
				// 商品项



				box-sizing: border-box;
				width: 694rpx;
				height: 178rpx;
				opacity: 1;
				border-radius: 14rpx;
				margin-bottom: 20rpx;
				background: rgba(255, 255, 255, 1);
				display: flex;

				padding-right: 23rpx;
				position: relative;

				.goodImage {
					// 商品图片

					margin-top: 14rpx;
					margin-left: 14rpx;
					padding-bottom: 8rpx;
					box-sizing: border-box;
					width: 158rpx;
					height: 158rpx;
					opacity: 1;
					border-radius: 8rpx;

					image {
						border-radius: 8rpx;
						width: 100%;
						height: 100%;
					}
				}

				.goodDesc {

					// 商品描述区域
					margin-left: 26rpx;
					margin-top: 15rpx;


					.goodName {
						// 商品名称
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
						width: 422rpx;
						font-size: 28rpx;
						max-height: 76rpx;
						margin-bottom: 10rpx;
					}

					.discount {
						// 折扣信息

						margin-top: 30rpx;
						font-size: 24rpx;
						font-weight: 400;
						letter-spacing: 0rpx;
						line-height: 34.76rpx;
						color: rgba(179, 130, 75, 1);
					}

					.priceAndNum {
						// 价格和数量区域
						margin-top: 20rpx;

						.price {
							// 价格区域

							.nowPrice {
								// 现价
								box-sizing: border-box;
								width: 200rpx;
								height: 54rpx;

								font-size: 36rpx;
								font-weight: 700;
								letter-spacing: 0rpx;
								line-height: 52.12rpx;
								color: rgba(212, 48, 48, 1);
								text-align: left;
								vertical-align: top;
								overflow: hidden;
								text-overflow: ellipsis;
							}

							.prePrice {
								// 原价
								margin-left: 20rpx;
								font-size: 24rpx;
								font-weight: 400;
								letter-spacing: 0rpx;
								line-height: 34.76rpx;
								text-decoration-line: line-through;
								color: rgba(167, 167, 167, 1);

							}
						}

						.steeper {
							// 数量调节器区域
							position: absolute;
							bottom: 25rpx;
							right: 23rpx;
							box-sizing: border-box;


							.goodsQuantity {
								width: 128rpx;
								height: 30rpx;
								opacity: 1;
								border-radius: 6rpx;
								background: rgba(212, 48, 48, 1);
								font-size: 20rpx;
								font-weight: 700;
								letter-spacing: 0rpx;
								line-height: 28.96rpx;
								color: rgba(255, 255, 255, 1);
								display: flex;
								justify-content: center;
								align-items: center;
							}

							.specitionSelect {
								margin-top: 4rpx;
								box-sizing: border-box;
								width: 128rpx;
								height: 44rpx;
								opacity: 1;
								border-radius: 6rpx;
								background: rgba(223, 161, 60, 1);
								font-size: 24rpx;
								font-weight: 500;
								letter-spacing: 0rpx;
								line-height: 34.76rpx;
								color: rgba(255, 255, 255, 1);
								display: flex;
								justify-content: center;
								align-items: center;

							}


							// 进货清单的进步器
							.steeperOperate {
								border: solid;
								width: 162rpx;
								height: 32rpx;

							}



						}
					}

					.specific {
						margin-top: 4rpx;
						font-size: 24rpx;
						font-weight: 400;
						letter-spacing: 0rpx;
						line-height: 34.76rpx;
						color: rgba(85, 85, 87, 1);
					}
				}
			}
		}

		// 配送细节
		.deliverDetail {
			background-color: rgba(255, 255, 255, 1);
			width: 692rpx;
			height: 166rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			align-items: center;
			border-radius: 14rpx;
			background: rgba(255, 255, 255, 1);
			margin-bottom: 30rpx;

			.deliverPrice {
				width: 632rpx;
				height: 83rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;


			}


			.remark {
				width: 632rpx;
				height: 83rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.textContent {
					white-space: nowrap;
					padding-right: 15rpx;

				}

				.displayText {
					display: flex;
					align-items: center;
					color: rgba(166, 166, 166, 1);

					input {
						text-align: right;
						text-overflow: ellipsis;
					}
				}


			}


		}

		// 支付板块
		.payContent {
			box-sizing: border-box;
			width: 692rpx;
			height: 224rpx;
			opacity: 1;
			border-radius: 14rpx;
			background: rgba(255, 255, 255, 1);
			display: flex;
			flex-direction: column;
			justify-content: space-around;

			.payTitle {

				box-sizing: border-box;
				font-size: 32rpx;
				font-weight: 400;
				letter-spacing: 0rpx;
				line-height: 46.34rpx;
				color: rgba(0, 0, 0, 1);
				margin-left: 20rpx;
			}

			.payItem {
				box-sizing: border-box;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;


				.title {

					display: flex;
					align-items: center;
					justify-content: center;
					padding-left: 30rpx;

					text {
						margin-left: 20rpx;
					}

					.wxIcon {
						box-sizing: border-box;
						width: 38rpx;
						height: 32.82rpx;
						background: url('/static/cart/spcar_icon_WeChat pay_default@2px.png.png');
						background-size: cover;
					}

					.commssionIcon {
						width: 36rpx;
						height: 36rpx;
						box-sizing: border-box;
						background: url('https://zhinengjiayi.oss-cn-chengdu.aliyuncs.com/my/user_icon_commission_default%404x.png');
						background-size: cover;
					}

					.insufficient {
						color: rgba(167, 167, 167, 1);
					}



				}

				.selectPay {
					margin-right: 30rpx;
					width: 32rpx;
					height: 32rpx;
					box-sizing: border-box;


				}

				.unselected {
					background: url('/static/cart/spcar_btu_ok_default@2px.png.png');
					background-size: cover;

				}

				.selected {
					background: url('/static/cart/spcar_btu_ok_pressed@2px.png.png');
					background-size: cover;
				}

			}

		}

		//订单提交板块
		.confirmFooter {
			z-index: 9999999;
			box-sizing: border-box;
			display: flex;
			width: 100%;
			height: 190rpx;
			position: fixed;
			bottom: 0;
			background: rgba(255, 255, 255, 1);

			.confirmContent {
				padding-left: 54rpx;
				width: 100%;
				justify-content: center;
				display: flex;
				margin-top: 20rpx;

				.textContent {
					height: 54rpx;
					display: flex;
					align-items: center;

					.price {
						margin-left: 10rpx;
						line-height: 52.12rpx;
						font-size: 36rpx;
						font-weight: 700;
						color: rgba(212, 48, 48, 1);
					}
				}


				.submit {
					margin-right: 30rpx;
					display: flex;
					align-items: center;
					text-align: center;
					justify-content: center;
					width: 230rpx;
					height: 74rpx;
					opacity: 1;
					font-size: 28rpx;
					border-radius: 26rpx;
					color: rgba(255, 255, 255, 1);
					background: rgba(212, 48, 48, 1);
				}


			}

		}
	}
</style>